import request from './utils/request';
import { BASE_URL } from './utils/request';
import {camelCase} from './utils/index'
import { checkDailySignIn } from './utils/utils';
// app.js
App({
  onLaunch: async function () {
    // 添加一个 Promise 用于处理登录状态
    this.loginReady = new Promise((resolve) => {
      this.loginReadyResolve = resolve;
    });
    
    try {
      await this.login();
    } catch (error) {
      console.error('应用启动失败:', error);
      wx.showToast({
        title: '应用启动失败，请重试',
        icon: 'none'
      });
    }
  },

  /**
   * 登录流程
   */
  async login() {
    try {
      const loginRes = await wx.login();
      if (!loginRes.code) {
        throw new Error('获取code失败: ' + loginRes.errMsg);
      }
      wx.request({
        url: `${BASE_URL}/login`,
        method: "POST",
        data: { code: loginRes.code },
        header: { 'Content-Type': 'application/json' },
        success: async (res) => {
          const result = camelCase(res.data)
          if (!result.data.token) {
            console.log('获取token失败');
          }
          this.globalData.userInfo =  result.data.user
          // 保存登录信息
          wx.setStorageSync('token', result.data.token);
          wx.setStorageSync('open_id', result.data.user.openId);
          // 获取用户信息
          await this.getUserInfo(result.data.user.openId);
          
          // 登录成功后，resolve loginReady promise
          this.loginReadyResolve(this.globalData.userInfo);
        },
        fail: (error) => {
          console.error('登录请求失败:', error);
          throw error;
        }
      });
    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  },

  getUserInfo: async function (open_id) {
    if (!open_id) {
      console.log('open_id不存在')
      return;
    }
    // guess.nezuko.cn/api/user
    return new Promise((resolve, reject) => {
      // 获取用户信息
      request({
        url: '/user',
        method: 'GET',
        data: {
          open_id: open_id
        }
      })
        .then((res) => {
          console.log('获取用户信息成功', res);
          if (res.data) {
            this.globalData.userInfo = res.data;
            resolve(res.data)
          }
        })
        .catch((err) => {
          console.error('请求失败', err);
        });
    });
  },
  // 全局数据
  globalData: {
    userInfo: null,
  }
});